package org.yohann.ai.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class JsonUtils {

    private static ObjectMapper objectMapper;

    public JsonUtils(ObjectMapper objectMapper) {
        JsonUtils.objectMapper = objectMapper;
    }

    public static <T> T readObject(String json, Class<T> clazz) {
        try {
            return objectMapper.reader().readValue(json, clazz);
        } catch (Exception e) {
            log.error("read object failed: {}", json, e);
        }
        return null;
    }

    public static String writeObject(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.error("write object failed: ", e);
        }
        return null;
    }

}
